package com.easy.component.network;

import android.content.ComponentName;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.easy.component.network.callback.CallBack;
import com.easy.component.network.exception.ApiException;
import com.easy.component.network.request.BaseBodyRequest;
import com.easy.component.network.request.Okhttp3DownloadTask;
import com.easy.component.network.request.Okhttp3FromTask;
import com.easy.component.network.utils.NetWorkLogger;
import com.google.gson.Gson;

import java.util.Map;

import okhttp3.Headers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 描述: {描述}
 * 作者:jack-song
 * 创建日期: 2017/10/18 14:56
 * 修改日期: 2017/10/18
 * 版本: {版本}
 */
public class EasyHttpManager extends BaseBodyRequest<EasyHttpManager> {
    private String TAG = EasyHttpManager.class.getName();
    /**
     *
     */
    private Call<ResponseBody> call;
    /**
     *
     */
    private CallBack callBack;

    public EasyHttpManager(String url) {
        super(url);
    }


    /**
     * post
     *
     * @param callBack
     */
    public void post(CallBack callBack) {
        execut(Method.POST, callBack);
    }

    /**
     * get
     *
     * @param callBack
     */
    public void get(CallBack callBack) {
        execut(Method.GET, callBack);
    }

    /**
     * get
     *
     * @param callBack
     */
    public void postForm(CallBack callBack) {
        executForm(callBack);
    }

    private void executForm(CallBack callBack) {
        new Okhttp3FromTask().sendMultipart(url, parameterForm, callBack);
    }

    /** 下载
     * @param destFileDir
     * @param destFileName
     * @param callBackLister
     */
    public void download(String destFileDir, String destFileName, CallBack callBackLister) {
        executdown(destFileDir, destFileName, callBackLister);
    }

    private void executdown(String destFileDir, String destFileName, CallBack callBackLister) {
        new Okhttp3DownloadTask().download(url, destFileDir, destFileName, callBackLister);
    }

    /**
     * 执行
     *
     * @param callBack
     */
    private void execut(int method, CallBack callBack) {
        call = build().executeRequest(method);
        this.callBack = callBack;
        if (null == this.callBack) {
            callBack.onError(new ApiException(new Throwable("---callBack is null---")));
            return;
        }
        if (null == call) {
            callBack.onError(new ApiException(new Throwable("---Call<ResponseBody> is null---")));
            return;
        }
        if (!call.isCanceled()) {
            call.enqueue(bodyCallback);
        }
    }

    /**
     * 取消
     */
    public void cancel() {
        if (null != call) {
            call.cancel();
        }
    }

    /**
     *
     */
    private Callback<ResponseBody> bodyCallback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                Headers headers = response.headers();
                try {
                    String headerCode = headers.get("code");
                    if (headerCode.equals("401") || headerCode.equals("406")) {
                        Intent intent = new Intent("com.zhineng.reversetreasure.broadcastreceiver.LogoutBroadcastReceiver.logout");
                        intent.setComponent(new ComponentName("com.zhineng.reversetreasure", "com.zhineng.reversetreasure.broadcastreceiver.LogoutBroadcastReceiver"));
                        EasyNetWork.getInstance().getContext().sendBroadcast(intent);
                        return;
                    }
                } catch (Exception e) {

                }
                String body = response.body().string() + "";
                NetWorkLogger.i(TAG, "---responseBody--->" + body);
                if (callBack.mType == String.class) {
                    callBack.onSuccess(body);
                } else {
                    callBack.onSuccess(new Gson().fromJson(body, callBack.mType));
                }

            } catch (Exception e) {
                e.printStackTrace();
                callBack.onError(new ApiException(e));
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            callBack.onError(new ApiException(t));
            NetWorkLogger.i(TAG, "---Throwable--->" + t.toString());
        }
    };

}
